/**
 * Created by jt on 2017/5/8.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import "../../../unit/common/js/bootstrap_js/table-editable.js";
import "../../../unit/common/js/bootstrap_js/jquery.jqGrid.src.js";

import applyListTpl from "./getapply.handlebars";

var token = sessionStorage.getItem('token');
if (token == null || token =='') {
    location.href = HOST_FRT+'/expert_grid/login.html';
}
var grdId = getArgs().id;
var projId = getArgs().projId;
if(!projId || !grdId){
    alert("参数错误！");
    location.href = HOST_FRT+'/expert_grid/proj_list.html';
}

var applyList = {
    pageNo: 1,
    pageSize: 1000,
    currTypList: [],  //币种
    currTyp: {},
    currVal: {},
    ScrDtls:{},     // 专家评标情况
    grdRul: 0,      // 评标规则  （0 最低单价中标；1 专家评标；2 最低总价中标）
    splrIds: {},
    editable: true,
    colapsedRow: [],
    init: function(){
        this.getCurrTypList()
            .then(this.getAllQotInfo)
            .then(this.renderapplyList)
            .then(this.bindEvent);
        this.viewGrdInf()
            .then(this.renderapplyList2);
    },

    // 查看评标结果
    viewGrdInf:function(){
        let self = applyList;
        return new Promise((resolve, reject)=>{
            jQuery.ajax({
                url: HOST_ADDR + '/cpmp/bidProjOnMngForExpt/viewGrdInf/' + grdId,
                type: 'get',
                dataType: 'json',
                contentType: "application/json",
                headers: { 'access_token': token, 'login_type': 'ums'},
                success: function (resp) {
                    if(resp.success && resp.msgCod=='S0000'){
                        console.log(resp);
                        if(typeof (resp.data.projInf.grdRul)!='undefined' && resp.data.projInf.grdRul!=null && resp.data.projInf.grdRul!='' ){
                            self.grdRul = resp.data.projInf.grdRul;
                        }
                        resp.data.projInf.projNam!=null  && $(".J_projNam").html(resp.data.projInf.projNam);

                        if(resp.data.projInf.projId!=projId){
                            alert("参数错误！");
                            return;
                        }
                        if(typeof(resp.data.projGrdSts)!='undefined' && resp.data.projGrdSts=='02'){ // 已提交，不可打分
                            $(".J_submit").remove();
                            self.editable = false;
                        }
                        resolve(resp.data.list);
                    }else{
                        alert(resp.msgCod + ' ' + resp.msgInf);
                        return;
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    },

    renderapplyList2:function(list){
        let self = applyList;
        if(self.grdRul=='0'){  // 最低单价评标
            $('.mygrid2').parent().removeClass("hide");;
            self.grdLowestUnitPrice(list);
        }else if(self.grdRul=='2'){ // 最低总价评标
            $('.mygrid3').parent().removeClass("hide");
            self.grdLowestSumPrice2(list);
        }else{
            $('.mygrid4').parent().removeClass("hide");
            self.grdAll(list);
        }
    },



    //   专家评分结果
    getApplyData: function() {
        return new Promise((resolve, reject)=>{
            let self = applyList;
            $.ajax({
                url: HOST_ADDR + `/cpmp/bidProjOnMngForExpt/getScrDtls/${self.pageNo}/${self.pageSize}/`+grdId,
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        self.ScrDtls = resp;
                        resolve();
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    },
    getCurrTypList:function(data){
        return new Promise((resolve, reject)=>{
            let self = applyList;
            let parmTyps = 'CURR_TYP';
            $.ajax({
                url: HOST_ADDR + '/cpmp/comParm/getByParmTyp/' + parmTyps,
                type: 'get',
                dataType: 'json',
                async: false,
                headers: {'access_token': token, 'login_type': 'ums'},
                contentType: 'application/json',
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + " - " + resp.msgInf);
                        console.log(resp.msgCod + " - " + resp.msgInf);
                        return;
                    }
                    if (jQuery.isArray(resp.data)) {
                        for (var i = 0; i < resp.data.length; i++) {
                            self.currTypList.push(resp.data[i].parmCod);
                            self.currTyp[resp.data[i].parmCod] = resp.data[i].parmMemo;
                            self.currVal[resp.data[i].parmCod] = resp.data[i].parmVal;
                            resolve();
                        }
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            })
        });
    },

    // 获取供应商报价信息
    getAllQotInfo: function(){
        return new Promise((resolve, reject)=>{
            let self = applyList;
            console.log(self);
            jQuery.ajax({
                url: HOST_ADDR + '/cpmp/bidProjOnMngForPchs/getOpenRcds/' + projId,
                type: 'get',
                dataType: 'json',
                contentType: "application/json",
                headers: {
                    'access_token': token, 'login_type': 'ums'
                },
                success: function (resp) {
                    if (resp.success && resp.msgCod=='S0000') {
                        resolve(resp.data);
                    } else {
                        alert(resp.msgCod + ' ' + resp.msgInf);
                        return;
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    },

    // 渲染列表
    renderapplyList: function(datalist){
        let self = applyList;
        if(datalist!=null){
            self.showTableData(datalist);
        }
    },

    // 供应商报价信息展示
    showTableData: function(datalist){
        let self = applyList;
        var colNames = ["物料编码","物料名称","单位","交货时间","交货地址"];
        var splrlists = [];
        var rows = [];   // 所有行数据
        var groupHeaders = [];
        var colModel = [
            {name:"matCod",index:"matCod",align:'left',width : 80,sortable : false, frozen:true},
            {name:"matNam",index:"matNam",align:'left',width : 120,sortable : false, frozen:true},
            {name:"matUnt",index:"matUnt",align:'left',width : 100,sortable : false},
            {name:"dlvDteStr",index:"dlvDteStr",align:'center',width : 120,sortable : false},
            {name:"dlvAdr",index:"dlvAdr",align:'center',width : 120,sortable : false}
        ];
        if(datalist.length){
            if(typeof(datalist[0].splrQotIoDtos) != 'undefined' && datalist[0].splrQotIoDtos.length){
                for(var i=0; i< datalist[0].splrQotIoDtos.length; i++){
                    splrlists.push(datalist[0].splrQotIoDtos[i].splrNam); // 参与报价的供应商列表,"单价","数量","币种"
                    groupHeaders.push({startColumnName:"price"+i,numberOfColumns:3,titleText:datalist[0].splrQotIoDtos[i].splrNam});
                    colNames.push("单价");
                    colNames.push("数量");
                    colNames.push("币种");
                    colModel.push({name:"price"+i,index:"price"+i,align:'center',width : 60,sortable : false});
                    colModel.push({name:"splNum"+i,index:"splNum"+i,align:'center',width : 60,sortable : false});
                    colModel.push({name:"currTyp"+i,index:"currTyp"+i,align:'center',width : 60,sortable : false,formatter: self.currTypFmatter});
                }
            }else{
                alert("数据异常！");
            }
        }

        for(var j=0;j<datalist.length;j++){
            var tmprow = {};
            tmprow.matCod = datalist[j].matCod;
            tmprow.matNam = datalist[j].matNam;
            tmprow.matUnt = datalist[j].matUnt ? datalist[j].matUnt : '';
            tmprow.dlvDteStr = datalist[j].dlvDte ? (new Date(datalist[j].dlvDte)).Format("yyyy-MM-dd") : '';
            tmprow.dlvAdr = datalist[j].dlvAdr ? datalist[j].dlvAdr : '';
            for(var k=0;k<datalist[j].splrQotIoDtos.length;k++){
                tmprow["price"+k] = datalist[j].splrQotIoDtos[k].price;
                tmprow["splNum"+k] = datalist[j].splrQotIoDtos[k].splNum;
                tmprow["currTyp"+k] = datalist[j].splrQotIoDtos[k].currTyp;
            }
            rows.push(tmprow);
        }

        $("#mygrid").jqGrid({
            width:'100%',
            height:'100%',
            dataType:'local',
            colNames:colNames,
            colModel:colModel,
            viewrecords:true,
            rowNum:-1,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true
        });
        $("#mygrid").jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders:groupHeaders
        });
        for ( var i = 0; i < rows.length; i++){
            $("#mygrid").jqGrid('addRowData', i + 1, rows[i]);
        }

        function resize(){
            if($("#mygrid").width()< $(".qotinfo").width()-100){
                $("#mygrid").jqGrid('setGridWidth', $(".qotinfo").width()-20);
            }
        }
        $(window).resize(function(){
            resize();
        });
        resize();

    },

    // 币种格式化
    currTypFmatter: function(cellvalue, options, rowObject){
        let self = applyList;
        if(typeof(cellvalue)=='undefined' || cellvalue==""){
            return "";
        }
        return self.currTyp[cellvalue];
    },

    // 最低单价评标
    grdLowestUnitPrice:function(datalist){
        let self = applyList;
        var totalLines = 1;  // 总数据行
        var matinfo = datalist;
        for(var i=0;i<datalist.length;i++){
            totalLines+=2;
        }
        jQuery("#mygrid2").jqGrid({
            width:'100%',
            dataType:'local',
            width:'100%',
            height: 250,
            colNames:['ID','物料编码','物料名称', '计量单位', '招标数量','交货地址','交货日期','备注'],
            colModel:[
                {name:'id',index:'id', width:50,hidden: true},
                {name:'matCod',index:'matCod', width:80},
                {name:'matNam',index:'matNam', width:150},
                {name:'matUnt',index:'matUnt', width:80,align:"center"},
                {name:'pchsNum',index:'pchsNum', width:80,align:"center"},
                {name:'dlvAdr',index:'dlvAdr', width:80},
                {name:'dlvDte',index:'dlvDte', width:120,align:"center"},
                {name:'memo',index:'memo', width:150}
            ],
            multiselect: false,
            subGrid: true,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            // define the icons in subgrid
            subGridOptions: {
                "plusicon"  : "ui-icon-triangle-1-e",
                "minusicon" : "ui-icon-triangle-1-s",
                "openicon"  : "ui-icon-arrowreturn-1-e",
                "reloadOnExpand" : true,
                "selectOnExpand" : true
            },
            subGridRowColapsed:function(subgrid_id, row_id){
                var subgrid_table_id = subgrid_id+"_t";
                if($("#"+subgrid_table_id)[0].p.savedRow.length){
                    $("#"+subgrid_table_id).jqGrid("saveCell", $("#"+subgrid_table_id)[0].p.savedRow[0].id, $("#"+subgrid_table_id)[0].p.savedRow[0].ic)
                }
                // var subids = $("#"+subgrid_table_id).jqGrid('getDataIDs');
                for(var m=0;m<matinfo[row_id-1].qotInfs.length;m++){
                    var subrowid = m+1;
                    var rowinfo = matinfo[row_id-1].qotInfs[m];
                    var dataObj = {};
                    rowinfo.grdOrd = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid).grdOrd;
                    rowinfo.grdRsn = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid).grdRsn;

                    dataObj.grdRsn = rowinfo.grdRsn;
                    dataObj.id = rowinfo.id;
                    dataObj.grdOrd = rowinfo.grdOrd;
                    dataObj.isRcmd = '0';
                    self.colapsedRow.push(dataObj);
                }
            },
            subGridRowExpanded: function(subgrid_id, row_id) {
                var subgrid_table_id, pager_id, lastsel;
                subgrid_table_id = subgrid_id+"_t";
                pager_id = "p_"+subgrid_table_id;
                $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
                jQuery("#"+subgrid_table_id).jqGrid({
                    datatype: "local",
                    height: '100%',
                    colNames: ['id','供应商ID','供应商','是否推荐中标','排名','币种','币种hidden','汇率','投标价格','应标数量','合计','应标交货日期','品牌','备注'],
                    colModel: [
                        {name:"id",index:"id",hidden:true},
                        {name:"splrId",index:"splrId",hidden:true},
                        {name:"splrNam",index:"splrNam",width:200, sortable:false},
                        {name:"isLowest",index:"isLowest",width:80,align:"center",sortable:false},
                        {name:"grdOrd",index:"grdOrd",width:80,align:"center", classes:"editable",sortable:false,editable:self.editable, formatter:'number'},
                        {name:"currTypFmt",index:"currTypFmt",width:70,align:"center", sortable:false,formatter: self.currTypFmatter},
                        {name:"currTyp",index:"currTyp",hidden:true},
                        {name:"exRat",index:"exRat",hidden:true},
                        {name:"uniPri",index:"uniPri",width:100,align:"center", sortable:false},
                        {name:"splNum",index:"splNum",width:100,align:"center", sortable:false},
                        {name:"ttlPri",index:"ttlPri",width:100,align:"center", sortable:false},
                        {name:"tendDlvDte",index:"tendDlvDte",width:130,align:"center", sortable:false},
                        {name:"matBnd",index:"matBnd",width:100,align:"center", sortable:false},
                        {name:"grdRsn",index:"grdRsn",width:100,align:"center", sortable:false,classes:"editable",editable:self.editable}
                    ],
                    fitColumns: true,
                    shrinkToFit: true,
                    altRows: true,
                    cellEdit: self.editable,
                    cellsubmit: 'clientArray',
                    onSelectRow : function(id) {
                        if (id && id !== lastsel) {
                            jQuery("#"+subgrid_table_id).jqGrid('saveRow', lastsel);
                            lastsel = id;
                        }
                    },
                    afterEditCell: function(a, b, c, d, e) { },
                    formatCell: function(a, b, c, d, e) { },
                    beforeSubmitCell: function(a, b, c, d, e) { },
                    beforeSaveCell: function(a, b, c, d, e) { },
                    afterSaveCell: function(a, b, c, d, e) { }
                });
                for(var m=0;m<matinfo[row_id-1].qotInfs.length;m++){
                    totalLines+=1;
                    var subrowid = m+1;
                    var rowinfo = matinfo[row_id-1].qotInfs[m];
                    rowinfo.isLowest = m==0 ? "是":"否";
                    if(rowinfo.grdOrd=='null' || rowinfo.grdOrd==0 || rowinfo.grdOrd==null){
                        rowinfo.grdOrd = m+1;
                    }
                    rowinfo.matBnd = rowinfo.matBnd ? rowinfo.matBnd : '';
                    rowinfo.tendDlvDte = rowinfo.tendDlvDte ? (new Date(rowinfo.tendDlvDte)).Format("yyyy-MM-dd") : '';
                    rowinfo.currTypFmt = rowinfo.currTyp;
                    rowinfo.ttlPri = rowinfo.ttlPri ? rowinfo.ttlPri : 0;
                    $("#"+subgrid_table_id).jqGrid('addRowData', subrowid, rowinfo);
                    $("#"+subgrid_table_id+" #"+subrowid).data("rowinfo",rowinfo);

                    if(self.colapsedRow.length){
                        for(var k=0,flag=true,len=self.colapsedRow.length;k<len;flag ? k++ : k){
                            if( self.colapsedRow[k]&&self.colapsedRow[k].id==rowinfo.id){
                                self.colapsedRow.splice(k,1);
                                flag = false;
                            } else {
                                flag = true;
                            }
                        }
                    }
                }
            }
        });
        for ( var i = 0; i < matinfo.length; i++){
            var rowid = i+1;
            matinfo.matId = matinfo.matId ? matinfo.matId : rowid;
            matinfo[i].dlvDte = matinfo[i].dlvDte ? (new Date(matinfo[i].dlvDte)).Format("yyyy-MM-dd") : '';
            $("#mygrid2").jqGrid('addRowData', rowid, matinfo[i]);
            $("#mygrid2>tbody>tr#"+rowid+">td").trigger("click");  // 报价信息展开
        }
        $("#mygrid2>tbody>tr.jqgrow").addClass("bg-lightgray");

        function resize(){
            var table_id = "mygrid2";
            var ids = $("#"+table_id).jqGrid("getDataIDs");
            for(var i=0;i<ids.length;i++){
                var subgrid_table_id = table_id+"_"+ids[i]+"_t";
                if($("#"+subgrid_table_id).width()+27<$(".mygrid2").width()){
                    $("#"+subgrid_table_id).jqGrid('setGridWidth', $(".mygrid2").width()-27);
                }
                $("#"+subgrid_table_id).parent().parent().width($("#"+subgrid_table_id).width()+2);
                $("#"+subgrid_table_id).parent().parent().prev().width($("#"+subgrid_table_id).width()+2);
            }
            jQuery("#mygrid2").jqGrid('setGridWidth', $("#mygrid2_1_t").width()+27);
            jQuery("#mygrid2").jqGrid('setGridHeight', totalLines*30+3*(matinfo.length+1));
        }
        $(window).resize(function(){
            resize();
        });
        resize();
    },


    // 最低总价评标
    grdLowestSumPrice2:function(datalist){
        let self = applyList;
        var colNames = ['ID','供应商名称','总价(RMB)','是否最低价','排名','备注'];
        var rows = [];   // 所有行数据
        var groupHeaders = [];
        var colModel = [
            {name:'splrId',index:'splrId', width:50,hidden: true},
            {name:'splrNam',index:'splrNam', width:150,frozen:true},
            {name:'ttlPri',index:'ttlPri', width:80,align:"center",frozen:true},
            {name:'isLowest',index:'isLowest',width:80,align:'center'},
            {name:'grdOrd',index:'grdOrd', width:70,editable:self.editable,classes:"editable",frozen:true,formatter:'number'},
            {name:'grdRsn',index:'grdRsn', width:150,editable:self.editable,classes:"editable",frozen:true}
        ];
        if(datalist.length){
            for(var i=0;i<datalist.length;i++){
                var splrId = datalist[i].splrId;
                var ids = [];
                if(datalist[i].grdOrd=='null' || datalist[i].grdOrd==0 || datalist[i].grdOrd==null){
                    datalist[i].grdOrd = i+1;
                }
                datalist[i].isLowest = i==0 ? "是":"否";
                for(var m=0;m<datalist[i].qotInfs.length;m++){
                    var matinfo = datalist[i].qotInfs[m];
                    console.log('-----',i,m,splrId);
                    if(i==0){
                        groupHeaders.push({startColumnName:"uniPri"+m,numberOfColumns:3,titleText:matinfo.matNam});
                        colNames.push("单价");
                        colNames.push("数量");
                        colNames.push("币种");
                        colModel.push({name:"uniPri"+m,index:"uniPri"+m,align:'center',width : 60,sortable : false});
                        colModel.push({name:"splNum"+m,index:"splNum"+m,align:'center',width : 60,sortable : false});
                        colModel.push({name:"currTyp"+m,index:"currTyp"+m,align:'center',width : 60,sortable : false,formatter: self.currTypFmatter});
                    }
                    datalist[i]["uniPri"+m] = matinfo.uniPri;
                    datalist[i]["splNum"+m] = matinfo.splNum;
                    datalist[i]["currTyp"+m] = matinfo.currTyp;
                    datalist[i]["matId"+m] = matinfo.matId;
                    datalist[i]["matNam"+m] = matinfo.matNam;
                    ids.push(matinfo.id);
                }
                rows.push(datalist[i]);
                self.splrIds[splrId] = ids;
            }
        }
        $("#mygrid3").jqGrid({
            width:'100%',
            height:'100%',
            dataType:'local',
            colNames:colNames,
            colModel:colModel,
            viewrecords:true,
            rowNum:-1,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            cellEdit: true,
            cellsubmit: 'clientArray',
            onSelectRow : function(id) {
                if (id && id !== lastsel) {
                    jQuery("#"+subgrid_table_id).jqGrid('saveRow', lastsel);
                    lastsel = id;
                }
            },
            afterEditCell: function(a, b, c, d, e) { },
            formatCell: function(a, b, c, d, e) { },
            beforeSubmitCell: function(a, b, c, d, e) { },
            beforeSaveCell: function(a, b, c, d, e) { },
            afterSaveCell: function(a, b, c, d, e) { }
        });
        $("#mygrid3").jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders:groupHeaders
        });
        for ( var i = 0; i < rows.length; i++){
            var rowid = i + 1;
            $("#mygrid3").jqGrid('addRowData', rowid, rows[i]);
            $("#mygrid3 #"+rowid).data("rowinfo",rows[i]);
        }

        function resize(){
            if($("#mygrid3").width()< $(".mygrid3").width()){
                $("#mygrid3").jqGrid('setGridWidth', $(".mygrid3").width()-20);
            }
            jQuery("#mygrid3").jqGrid('setGridHeight', (rows.length)*32);
        }
        $(window).resize(function(){
            resize();
        });
        resize();
    },

    // 综合评标
    grdAll:function(datalist){
        let self = applyList;
        var colNames = ["物料编码","物料名称","交货时间","交货地址"];
        var splrlists = [];
        var rows = [];   // 所有行数据
        var groupHeaders = [];
        var userData = {};
        var colModel = [
            {name:"matCod",index:"matCod",align:'left',width : 80,sortable : false},
            {name:"matNam",index:"matNam",align:'left',width : 120,sortable : false},
            {name:"dlvDteStr",index:"dlvDteStr",align:'center',width : 80,sortable : false},
            {name:"dlvAdr",index:"dlvAdr",align:'center',width : 80,sortable : false}
        ];
        if(datalist.length){
            if(typeof(datalist[0].splrQotIoDtos) != 'undefined' && datalist[0].splrQotIoDtos.length){
                for(var i=0; i< datalist[0].splrQotIoDtos.length; i++){
                    splrlists.push(datalist[0].splrQotIoDtos[i].splrNam); // 参与报价的供应商列表,"单价","数量","币种"
                    groupHeaders.push({startColumnName:"price"+i,numberOfColumns:3,titleText:datalist[0].splrQotIoDtos[i].splrNam});
                    colNames.push("单价");
                    colNames.push("数量");
                    colNames.push("币种");
                    colModel.push({name:"price"+i,index:"price"+i,align:'center',width : 60,sortable : false});
                    colModel.push({name:"splNum"+i,index:"splNum"+i,align:'center',width : 60,sortable : false});
                    // colModel.push({name:"currTyp"+i,index:"currTyp"+i,align:'center',width : 60,sortable : false,formatter: self.currTypFmatter});
                    colModel.push({name:"currTypFmt"+i,index:"currTypFmt"+i,align:'center',width : 60,sortable : false});
                    userData["price"+i] = "---11-----";
                    userData["splNum"+i] = "<button class='btn' splrId='"+datalist[0].splrQotIoDtos[i].splrId+"'>确认</button>";
                    userData["currTypFmt"+i] = "---22-----";
                }
            }else{
                alert("数据异常！");
            }
        }
        console.log(userData);
        for(var j=0;j<datalist.length;j++){
            var tmprow = {};
            tmprow.matCod = datalist[j].matCod;
            tmprow.matNam = datalist[j].matNam;
            tmprow.matUnt = datalist[j].matUnt ? datalist[j].matUnt : '';
            tmprow.dlvDteStr = datalist[j].dlvDte ? (new Date(datalist[j].dlvDte)).Format("yyyy-MM-dd") : '';
            tmprow.dlvAdr = datalist[j].dlvAdr ? datalist[j].dlvAdr : '';
            for(var k=0;k<datalist[j].splrQotIoDtos.length;k++){
                tmprow["price"+k] = datalist[j].splrQotIoDtos[k].price;
                tmprow["splNum"+k] = datalist[j].splrQotIoDtos[k].splNum;
                tmprow["currTyp"+k] = datalist[j].splrQotIoDtos[k].currTyp;
                tmprow["currTypFmt"+k] = self.currTyp[datalist[j].splrQotIoDtos[k].currTyp];
            }
            rows.push(tmprow);
        }

        $("#mygrid4").jqGrid({
            width:'100%',
            height:'100%',
            dataType:'local',
            colNames:colNames,
            colModel:colModel,
            viewrecords:true,
            rowNum:-1,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            loadonce: true,
            footerrow: true,
            userDataOnFooter: true,
            gridComplete:function(){
                $("#mygrid4").footerData("set",userData);
            }
        });
        $("#mygrid4").jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders:groupHeaders
        });
        for ( var i = 0; i < rows.length; i++){
            $("#mygrid4").jqGrid('addRowData', i + 1, rows[i]);
        }

        function resize(){
            if($("#mygrid4").width()< $(".mygrid4").width()){
                $("#mygrid4").jqGrid('setGridWidth', $(".mygrid4").width()-20);
            }
            jQuery("#mygrid4").jqGrid('setGridHeight', (rows.length)*32);
        }
        $(window).resize(function(){
            resize();
        });
        resize();
    },
    // 绑定事件
    bindEvent: function(){
        let self = applyList;
        // 专家打分
        $(".J_submit").unbind().click(function(){
            var self = applyList;
            var list = self.getPostData();
            var data = {};
            if(list.length){
                data.grdId = grdId;
                data.list = list;
            }else{
                return false;
            }
            jQuery.ajax({
                url: HOST_ADDR+'/cpmp/bidProjOnMngForExpt/postGrdInf',
                type: 'post',
                data: JSON.stringify(data),
                dataType: 'json',
                async: false,
                contentType:"application/json",
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                success: function(resp){
                    if (!resp.success) {
                        console.log(resp.msgCod+' '+resp.msgInf);
                        return;
                    }
                    console.log('评标成功！');
                    alert("评标成功！");
                    location.href = '/expert_grid/proj_list.html';
                },
                error:function(err){
                    console.log(err);
                }
            });
        });
    },

    // 获取要提交的表单数据
    getPostData: function(){
        let self = applyList;
        if(self.grdRul=='0'){ // 最低单价评标
            var table_id = "mygrid2";
            var ids = $("#"+table_id).jqGrid("getDataIDs");
            var datalist = [];
            for(var i=0;i<ids.length;i++){
                var matinfo = $("#mygrid2").jqGrid("getRowData",ids[i]);
                console.log(i,ids[i],matinfo);

                var subgrid_table_id = table_id+"_"+ids[i]+"_t";
                if($("#"+subgrid_table_id).length==0){  // 数据行已经收缩起来了
                    continue;
                }
                var subids = $("#"+subgrid_table_id).jqGrid('getDataIDs');
                // var rcmdCount = $("#"+subgrid_table_id).getCol("isRcmd",false,"sum");  // 每个物料下面设置为推荐的数量
                // var markednm = 0;
                if($("#"+subgrid_table_id)[0].p.savedRow.length){
                    $("#"+subgrid_table_id).jqGrid("saveCell", $("#"+subgrid_table_id)[0].p.savedRow[0].id, $("#"+subgrid_table_id)[0].p.savedRow[0].ic)
                }
                if(subids.length){
                    for(var j=0;j<subids.length;j++){
                        var dataObj = {};
                        $("#"+subgrid_table_id).saveRow(subids[j], false, 'clientArray');
                        var content = $("#"+subgrid_table_id).jqGrid("getRowData",subids[j]);
                        if(content.grdOrd==null || content.grdOrd==''){
                            alert("请填写排名");
                            return false;
                        }
                        dataObj.grdRsn = content.grdRsn;
                        dataObj.id = content.id;
                        dataObj.grdOrd = content.grdOrd;
                        dataObj.isRcmd = content.isRcmd=='1' ? '1' : '0';
                        // if(content.isRcmd == '1'){
                        //     markednm ++;
                        // }
                        // dataObj.grdOrd = (content.isRcmd == '1' ? markednm : j+1+rcmdCount-markednm);
                        datalist.push(dataObj);
                    }
                }
            }
            var resultList = datalist.concat(self.colapsedRow);  // 合并收起来的数据
            return resultList;
        }else if(self.grdRul=='2'){ // 最低总价评标
            var allids = $("#mygrid3").jqGrid("getDataIDs");
            var datalist = [];
            if($("#mygrid3")[0].p.savedRow.length){
                $("#mygrid3").jqGrid("saveCell", $("#mygrid3")[0].p.savedRow[0].id, $("#mygrid3")[0].p.savedRow[0].ic)
            }
            var rcmdCount = $("#mygrid3").getCol("isRcmd",false,"sum");  // 设置为推荐的数量
            var markednm = 0;
            for(var i=0;i<allids.length;i++){
                var content = $("#mygrid3").jqGrid("getRowData",allids[i]);
                var ids = self.splrIds[content.splrId];
                if(content.grdOrd==null || content.grdOrd==''){
                    alert("请填写排名");
                    return false;
                }
                var grdOrd = content.grdOrd;
                // if(content.isRcmd == '1'){
                //     markednm ++;
                // }
                // var grdOrd = (content.isRcmd == '1' ? markednm : i+1+rcmdCount-markednm);
                // if(content.grdRsn==null || content.grdRsn==''){
                //     alert("请填写评标理由！");
                //     return false;
                // }else{
                // }
                for(var m=0;m<ids.length;m++){
                    var dataObj = {};
                    dataObj.grdRsn = content.grdRsn;
                    dataObj.id = ids[m];
                    dataObj.isRcmd = content.isRcmd=='1' ? '1' : '0';
                    dataObj.grdOrd = grdOrd;
                    datalist.push(dataObj);
                }
            }
            return datalist;
        }
    },

};

App.init();
applyList.init();

